/*
Copyright The Helm Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Generates the default versions to use with capabilities. This cannot be loaded
// dynamically as it uses enough memory to cause out of memory issues in CI.
//
// +build ignore
package main

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"os"
	"path"
	"sort"

	"k8s.io/client-go/kubernetes/scheme"
)

const licenseHeader = `/*
Copyright The Helm Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/`

func main() {
	v := getVersions()

	o := createOutput(v)

	err := ioutil.WriteFile("capabilities_versions_generated.go", o, 0644)
	if err != nil {
		fmt.Printf("writing output: %s", err)
		os.Exit(1)
	}
}

func createOutput(v []string) []byte {
	var out bytes.Buffer

	fmt.Fprintln(&out, licenseHeader)
	fmt.Fprintln(&out, "// Code generated by capabilities_default_versions_generate.go; DO NOT EDIT.")
	fmt.Fprint(&out, "package chartutil\n\n")
	fmt.Fprintln(&out, "func defaultVersions() []string {")
	fmt.Fprintln(&out, "\treturn []string{")

	for _, v := range v {
		fmt.Fprintf(&out, "\t\t\"%s\",\n", v)
	}

	fmt.Fprintln(&out, "\t}")
	fmt.Fprintln(&out, "}")

	return out.Bytes()
}

func getVersions() []string {

	var s []string
	var gv string
	var gvk string

	// Check is used so that we only add an item once to the return
	check := make(map[string]struct{})

	// Client go has a default scheme set with everything in it
	// This includes over 500 group versions and group versioned kinds
	for k := range scheme.Scheme.AllKnownTypes() {
		gv = path.Join(k.Group, k.Version)
		gvk = path.Join(k.Group, k.Version, k.Kind)
		if _, ok := check[gv]; !ok {
			check[gv] = struct{}{}
			s = append(s, gv)
		}
		if _, ok := check[gvk]; !ok {
			check[gvk] = struct{}{}
			s = append(s, gvk)
		}
	}

	// Put the names in a consistent order
	sort.Strings(s)

	return s
}
